package sziit.znk.factory;

import sziit.znk.annotation.bean.*;
import sziit.znk.utils.Enum.ClassType;
import sziit.znk.utils.IfComponent;
import sziit.znk.utils.importothers.ClassUtil;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

public class ScanNewBean {

    private static Map<String, Object> beanContainer = null;

    static {
        beanContainer = BeanFactory.getBeanContainer();
    }

    public ScanNewBean(String packageName) {
        List<Class<?>> classes = ClassUtil.getClasses(packageName);

        for (Class<?> clazz : classes) {
            try {
                Class<?> aClass = Class.forName(clazz.getName());
                Annotation[] annotations = aClass.getAnnotations();
                boolean flag = false;
                for (Annotation annotation : annotations) {
                    if (IfComponent.havingComponentAnnotation(annotation)) flag = true;
                }
                if (flag) {
                    Object o = aClass.getConstructor().newInstance();
                    String name = aClass.getName();
                    String[] strings = name.replace(".", "/").split("/");
                    int length = strings.length;
                    String beanId = strings[length - 1].substring(0, 1).toLowerCase() + strings[length - 1].substring(1);
                    beanContainer.put(beanId, o);
                }
                Method[] methods = aClass.getDeclaredMethods();
                for (Method method : methods) {
                    if (method.getAnnotation(Bean.class) != null) {
                        Object o = clazz.getConstructor().newInstance();
                        Object getObject = method.invoke(o, null);
                        String name = getObject.getClass().getName();
                        String[] strings = name.replace(".", "/").split("/");
                        int length = strings.length;
                        String beanId = strings[length - 1].substring(0, 1).toLowerCase() + strings[length - 1].substring(1);
                        beanContainer.put(beanId, getObject);
                    }
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        new ScanAutoWireBean(packageName);
    }
}
